package com.xiaozhengkeji.minecraft.plugin.fishplus.base;

import com.xiaozhengkeji.minecraft.plugin.fishplus.config.FishConfig;
import com.xiaozhengkeji.minecraft.plugin.fishplus.entity.PlayerDataEntity;
import com.xiaozhengkeji.minecraft.plugin.fishplus.listener.PlayerCustomFishListener;
import com.xiaozhengkeji.minecraft.plugin.fishplus.utils.EncryptUtil;
import org.bukkit.configuration.file.YamlConfiguration;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.UUID;

/**
 * 内存数据管理
 */
public class MemoryBase {
    /**
     * 玩家定制化钓鱼事件监听器
     * <p>
     * 玩家退服 进服时进行注册和注销
     */
    public static HashMap<UUID, PlayerCustomFishListener> PLAYER_CUSTOM_FISH_LISTENER_HASH_MAP = new LinkedHashMap<>();

    /**
     * 玩家数据内存
     */
    public static HashMap<UUID, String> PLAYER_DATA_PATH_HASH_MAP = new LinkedHashMap<>();

    /**
     * 获取指定玩家的数据
     */
    public static PlayerDataEntity getPlayerData(UUID uuid) {
        String temp_data_path = PLAYER_DATA_PATH_HASH_MAP.get(uuid);
        YamlConfiguration temp_data = YamlConfiguration.loadConfiguration(new File(temp_data_path));
        String temp_data_str = EncryptUtil.Base64Decrypt(temp_data.getString("base"));
        return PlayerDataEntity.buildPlayerDataEntity(temp_data_str);
    }

    /**
     * 存储指定玩家的数据
     */
    public static Boolean savePlayerData(PlayerDataEntity playerDataEntity) {
        String temp_data_path = PLAYER_DATA_PATH_HASH_MAP.get(UUID.fromString(playerDataEntity.PlayerUUID));
        YamlConfiguration temp_data = YamlConfiguration.loadConfiguration(new File(temp_data_path));
        temp_data.set("base", EncryptUtil.Base64Encryption(playerDataEntity.toJsonString()));
        try {
            temp_data.save(temp_data_path);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 对一个玩家的数据进行初始化 归零
     */
    public static boolean initializePlayerData(UUID uuid) {
        String temp_data_path = PLAYER_DATA_PATH_HASH_MAP.get(uuid);
        YamlConfiguration temp_data = YamlConfiguration.loadConfiguration(new File(temp_data_path));
        PlayerDataEntity temp_player_data = new PlayerDataEntity();
        temp_player_data.PlayerUUID = uuid.toString();
        temp_player_data.MaxLucky = 0;
        temp_player_data.MaxNumFishing = 0;
        temp_player_data.MaxNumFishing_Success = 0;
        temp_data.set("base", EncryptUtil.Base64Encryption(temp_player_data.toJsonString()));
        /*        temp_data.set("fish.log", new LinkedList<>());*/
        try {
            temp_data.save(temp_data_path);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

}
